<template>
  <div class="customer-service-page">
    <div class="container">
      <!-- 头部 -->
      <div class="header">
        <h1 class="title">💬 客服咨询</h1>
        <div class="status-info">
          <span class="status-label">连接状态：</span>
          <span class="status-badge" :class="{ connected: isConnected }">
            {{ isConnected ? '🟢 已连接' : '🔴 未连接' }}
          </span>
        </div>
      </div>

      <!-- 连接提示（未连接时显示，自动连接） -->
      <div v-if="!isConnected" class="service-selection">
        <div class="selection-card">
          <h3>客服咨询</h3>
          <div class="loading">{{ loadingAdmin ? '正在连接管理员...' : (adminId ? '正在建立连接...' : '无法获取管理员信息') }}</div>
        </div>
      </div>

      <!-- 聊天区域（连接后显示） -->
      <div v-else class="chat-container">
        <div class="chat-header">
          <div class="service-info">
            <span class="service-icon">👤</span>
            <span class="service-name">管理员（ID: {{ adminId }}）</span>
            <span class="service-status online">在线</span>
          </div>
          <button class="disconnect-btn" @click="disconnect">退出</button>
        </div>

        <div class="messages-container" ref="messagesContainer">
          <div
            v-for="(msg, index) in messages"
            :key="index"
            class="message-item"
            :class="msg.type"
          >
            <div v-if="msg.type === 'system'" class="system-message">
              <span class="system-icon">ℹ️</span>
              <span>{{ msg.content }}</span>
            </div>
            <div v-else-if="msg.type === 'chat'" class="chat-message" :class="msg.from === 'user' ? 'mine' : 'other'">
              <div class="message-header">
                <span class="sender-name">{{ msg.from === 'user' ? '我' : '客服' }}</span>
                <span class="message-time">{{ msg.time }}</span>
              </div>
              <div class="message-content">{{ msg.content }}</div>
            </div>
            <div v-else-if="msg.type === 'error'" class="error-message">
              <span class="error-icon">⚠️</span>
              <span>{{ msg.content }}</span>
            </div>
          </div>
        </div>

        <div class="input-area">
          <input
            v-model="messageInput"
            type="text"
            placeholder="输入消息..."
            class="message-input"
            @keyup.enter="sendMessage"
            :disabled="!isConnected"
          />
          <button
            class="send-btn"
            @click="sendMessage"
            :disabled="!isConnected || !messageInput.trim()"
          >
            发送
          </button>
        </div>
      </div>

      <!-- 提示对话框：客服不在线等错误 -->
      <div v-if="showModal" class="modal-mask">
        <div class="modal-dialog">
          <div class="modal-title">提示</div>
          <div class="modal-content">{{ modalText }}</div>
          <div class="modal-actions">
            <button class="modal-btn" @click="showModal = false">我知道了</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { customerServiceWS } from '@/utils/customerServiceWebSocket'
import api from '@/api/index'

const userStore = useUserStore()
const router = useRouter()

// 状态
const isConnected = ref(false)
const loadingAdmin = ref(false)
const adminId = ref('')
const messages = ref([])
const messageInput = ref('')
const messagesContainer = ref(null)

// 错误对话框
const showModal = ref(false)
const modalText = ref('')

let messageHandler = null

// 获取管理员ID
const fetchAdminId = async () => {
  loadingAdmin.value = true
  try {
    // 调用API获取管理员ID
    const response = await api.get('/user/admin-id')
    if (response && response.code === 200 && response.data && response.data.admin_id) {
      adminId.value = String(response.data.admin_id)
      // 获取到管理员ID后自动连接
      connectToAdmin()
    } else {
      messages.value.push({
        type: 'error',
        content: '无法获取管理员ID，请确保管理员已存在',
        time: new Date().toLocaleTimeString()
      })
    }
  } catch (error) {
    console.error('获取管理员ID失败:', error)
    messages.value.push({
      type: 'error',
      content: '获取管理员信息失败，请刷新页面重试',
      time: new Date().toLocaleTimeString()
    })
  } finally {
    loadingAdmin.value = false
  }
}

// 连接到管理员
const connectToAdmin = () => {
  if (!adminId.value) {
    messages.value.push({
      type: 'error',
      content: '管理员ID不存在，请刷新页面重试',
      time: new Date().toLocaleTimeString()
    })
    return
  }

  if (!userStore.isLoggedIn || !userStore.userInfo) {
    messages.value.push({
      type: 'error',
      content: '请先登录',
      time: new Date().toLocaleTimeString()
    })
    return
  }

  const userId = userStore.userInfo.id
  const userName = userStore.userInfo.name || userStore.userInfo.username || userStore.userInfo.nickname || `用户${userId}`
  
  // 连接WebSocket
  const success = customerServiceWS.connectAsUser(userId, userName, adminId.value)
  
  if (success) {
    // 监听消息
    messageHandler = customerServiceWS.onMessage((message) => {
      handleMessage(message)
    })
    
    // 监听连接状态
    checkConnectionStatus()
  } else {
    messages.value.push({
      type: 'error',
      content: '连接失败，请重试',
      time: new Date().toLocaleTimeString()
    })
  }
}

// 检查连接状态
const checkConnectionStatus = () => {
  const interval = setInterval(() => {
    isConnected.value = customerServiceWS.isConnected
    if (!isConnected.value) {
      clearInterval(interval)
    }
  }, 500)
}

// 处理收到的消息
const handleMessage = (message) => {
  if (message.type === 'system') {
    messages.value.push({
      type: 'system',
      content: message.message || '系统消息',
      time: new Date().toLocaleTimeString()
    })
    isConnected.value = true
  } else if (message.type === 'chat') {
    messages.value.push({
      type: 'chat',
      from: message.from === 'service' ? 'service' : 'user',
      content: message.content,
      time: message.time || new Date().toLocaleTimeString()
    })
    scrollToBottom()
  } else if (message.type === 'error') {
    const text = message.message || '客服不在线'
    messages.value.push({
      type: 'error',
      content: text,
      time: new Date().toLocaleTimeString()
    })
    modalText.value = text
    showModal.value = true
    isConnected.value = false
  }
}

// 发送消息
const sendMessage = () => {
  if (!messageInput.value.trim() || !isConnected.value) {
    return
  }

  const content = messageInput.value.trim()
  
  // 用户端发送消息（不需要指定to_user，会自动发送给绑定的客服）
  const success = customerServiceWS.sendMessage(null, content)
  
  if (success) {
    // 添加到消息列表
    messages.value.push({
      type: 'chat',
      from: 'user',
      content: content,
      time: new Date().toLocaleTimeString()
    })
    messageInput.value = ''
    scrollToBottom()
  } else {
    messages.value.push({
      type: 'error',
      content: '发送失败，请检查连接状态',
      time: new Date().toLocaleTimeString()
    })
  }
}

// 断开连接
const disconnect = () => {
  customerServiceWS.disconnect()
  isConnected.value = false
  adminId.value = ''
  if (messageHandler) {
    messageHandler()
    messageHandler = null
  }
  messages.value.push({
    type: 'system',
    content: '已断开连接',
    time: new Date().toLocaleTimeString()
  })
  // 退出当前页面
  setTimeout(() => {
    if (window.history.length > 1) {
      router.back()
    } else {
      router.replace('/')
    }
  }, 0)
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 初始化
onMounted(() => {
  fetchAdminId()
})

// 清理
onUnmounted(() => {
  if (messageHandler) {
    messageHandler()
  }
  if (isConnected.value) {
    customerServiceWS.disconnect()
  }
})
</script>

<style scoped>
.customer-service-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.container {
  max-width: 900px;
  margin: 0 auto;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-label {
  font-size: 14px;
  opacity: 0.9;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.2);
  font-size: 14px;
  font-weight: 500;
}

.status-badge.connected {
  background: rgba(34, 197, 94, 0.3);
}

.service-selection {
  padding: 40px;
}

.selection-card {
  text-align: center;
}

.selection-card h3 {
  font-size: 20px;
  margin-bottom: 24px;
  color: #1f2937;
}

.loading {
  padding: 40px;
  color: #6b7280;
}

.no-services {
  padding: 40px;
  color: #6b7280;
}

.no-services p {
  margin: 8px 0;
}

.hint {
  font-size: 14px;
  color: #9ca3af;
}

.connect-info {
  text-align: center;
  padding: 20px;
}

.connect-info p {
  margin-bottom: 20px;
  color: #374151;
  font-size: 16px;
}

.connect-btn {
  padding: 12px 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.connect-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 600px;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.service-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.disconnect-btn {
  padding: 8px 16px;
  background: #ef4444;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.disconnect-btn:hover {
  background: #dc2626;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background: #fafafa;
}

.message-item {
  margin-bottom: 16px;
}

.system-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #e0e7ff;
  border-radius: 8px;
  color: #3730a3;
  font-size: 14px;
  text-align: center;
  justify-content: center;
}

.error-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #fee2e2;
  border-radius: 8px;
  color: #991b1b;
  font-size: 14px;
  text-align: center;
  justify-content: center;
}

.chat-message {
  max-width: 70%;
}
.chat-message.other { /* 对方（客服）在左 */
  margin-right: auto;
}
.chat-message.mine { /* 我在右 */
  margin-left: auto;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.sender-name {
  font-weight: 600;
  color: #1f2937;
  font-size: 14px;
}

.message-time {
  font-size: 12px;
  color: #6b7280;
}

.message-content {
  padding: 12px 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  color: #1f2937;
  line-height: 1.5;
  word-break: break-word;
}

.chat-message.mine .message-content {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

/* 模态框样式 */
.modal-mask {
  position: fixed;
  left: 0; right: 0; top: 0; bottom: 0;
  background: rgba(0,0,0,.35);
  display: flex;
  align-items: center;
  justify-content: center;
}
.modal-dialog {
  width: 320px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0,0,0,.2);
  overflow: hidden;
}
.modal-title {
  padding: 12px 16px;
  font-weight: 600;
  background: #f3f4f6;
}
.modal-content {
  padding: 16px;
  color: #374151;
}
.modal-actions {
  padding: 12px 16px;
  display: flex;
  justify-content: flex-end;
}
.modal-btn {
  padding: 8px 14px;
  background: #667eea;
  color: #fff;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

.input-area {
  display: flex;
  gap: 12px;
  padding: 16px 24px;
  background: white;
  border-top: 1px solid #e5e7eb;
}

.message-input {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;
}

.message-input:focus {
  border-color: #667eea;
}

.message-input:disabled {
  background: #f3f4f6;
  cursor: not-allowed;
}

.send-btn {
  padding: 12px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.send-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>


